package cn.itcast.flink.transformation;

import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.ArrayList;
import java.util.List;

/**
 * Author itcast
 * Date 2022/1/11 17:17
 * Desc TODO
 */
public class KeyedDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //keyBy支持几种类型？ 两种 ① 元祖 Tuple ② Pojo 普通的java类
        /*DataStreamSource<Tuple2<String, Integer>> source = env
                .fromElements(Tuple2.of("男", 1), Tuple2.of("男", 1), Tuple2.of("女", 1), Tuple2.of("男", 1));*/
        List<User> users = new ArrayList<>();
        //
        users.add(new User("男", 1));
        users.add(new User("男", 1));
        users.add(new User("女", 1));
        users.add(new User("男", 1));
        users.add(new User("女", 1));
        DataStreamSource<User> source1 = env.fromCollection(users);
        //keyBy分组
        /*source.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            @Override
            public String getKey(Tuple2<String, Integer> value) throws Exception {
                return value.f0;
            }
        }).sum(1).printToErr();*/
        source1.keyBy(new KeySelector<User, String>() {
            @Override
            public String getKey(User value) throws Exception {
                return value.getGender();
            }
        }).reduce(new ReduceFunction<User>() {
            @Override
            public User reduce(User value1, User value2) throws Exception {
                return new User(value2.gender, value1.num + value2.num);
            }
        }).printToErr();
        env.execute();
    }

    public static class User {
        private String gender;
        private Integer num;

        public User(String gender, int num) {
            this.gender = gender;
            this.num = num;
        }

        public String getGender() {
            return gender;
        }

        public void setGender(String gender) {
            this.gender = gender;
        }

        public int getNum() {
            return num;
        }

        public void setNum(int num) {
            this.num = num;
        }

        @Override
        public String toString() {
            return "User{" +
                    "gender='" + gender + '\'' +
                    ", num=" + num +
                    '}';
        }
    }
}
